/* 
 *
 * Persistence4J - Simple library for data persistence using java
 * Copyright (c) 2010, Avdhesh yadav.
 * http://www.avdheshyadav.com
 * Contact: avdhesh.yadav@gmail.com
 *
 * This library is free software; you can redistribute it and/or modify it under the terms
 * of the GNU Lesser General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this
 * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 */

package com.avdy.p4j.jdbc.id;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.List;

import org.apache.commons.id.IdentifierGenerator;
import org.apache.commons.id.serial.LongGenerator;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

/**
 * 
 * @author Avdhesh yadav
 */
public class IdGeneratorServiceImpl implements IdGeneratorService
{
	/** */
	private static final long serialVersionUID = 1L;
	/** */
	private static IdGeneratorService mInstance;
	/** */
	private  File mIdFile;
	/** */
	private IdentifierGenerator mIdGenerator;
	/** */
	private static final boolean wrapping = false;
	
	private boolean initialized = false;
	
	
	/**
	 * 
	 * @throws RemoteException
	 */
	private IdGeneratorServiceImpl()
	{
		super();
	}
	
	/**
	 * 
	 * @return IdGeneratorService
	 */
	public static IdGeneratorService getInstance()
	{
		if(mInstance == null)
		{
			mInstance = new IdGeneratorServiceImpl();
		}	
		return mInstance;
	}
	
	
	/**
	 * 
	 * @throws Exception
	 */
	public void initIdGenerator(String idFile) throws IOException
	{
		if(initialized)
			throw new RuntimeException("IdGenerator is already Initilized");
		
		long initialValue = 0L;
		mIdFile = new File(idFile);
		if(mIdFile.isFile() && mIdFile.exists())
		{
			List<String> lines = FileUtils.readLines(mIdFile);
			if(lines != null && lines.size() > 0)
			{
				String line = lines.get(0);
				if(line!= null && (!line.isEmpty()) && StringUtils.isNumeric(line))
					initialValue = Long.parseLong(line);
			}
		}
		else
		{
			mIdFile.createNewFile();
		}
		// we increment 1 to this initial value so that we get the nextIdentifier after old identifier.
		initialValue = initialValue + 1;
		mIdGenerator = new LongGenerator(wrapping , initialValue);
		initialized = true;
	}
	
	
	/**
	 *  
	 * @param identifierGenerator IdentifierGenerator
	 */
	public void setIdentifierGenerator(IdentifierGenerator identifierGenerator)
	{
		if(mIdGenerator == null)
			mIdGenerator = identifierGenerator;
		else
			throw new RuntimeException("IdentifierGenerator is already set");
	}
	
	
	/**
	 *  
	 * @param identifierGenerator IdentifierGenerator
	 */
	public void setIdFile(File idFile)
	{
		if(mIdFile == null)
			mIdFile = idFile;
		else
			throw new RuntimeException("idFile is already set");
	}
	
	
	/**
     * Gets the next identifier in the sequence.
     *
     * @return the next identifier in sequence
     */
	public Object nextIdentifier()
    {
		if(mIdGenerator == null || mIdFile == null)
			throw new RuntimeException("No IdentifierGenerator is Registered.Please Register IdentifierGenerator First");

		Object identifier = mIdGenerator.nextIdentifier();
		try 
		{
			updateIdFile(mIdFile,String.valueOf((identifier)));
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
		return identifier;
    }
	
	
	/**
	 * 
	 * @param idFile File
	 * @param identifier String
	 * 
	 * @throws IOException 
	 */
	private static void updateIdFile(File idFile , String identifier) throws IOException
	{
		OutputStream fileOutputStream = new FileOutputStream(idFile);
		OutputStreamWriter osw = new OutputStreamWriter(fileOutputStream);
		BufferedWriter bw = new BufferedWriter(osw);
		bw.write(identifier);
		bw.close();
	}
	
	
	/**
	 * 
	 */
	public Object clone()throws CloneNotSupportedException
	{
		throw new CloneNotSupportedException(); 
	}
}